<template>
  <div>
    <el-dialog v-model="props.TagVisible" :title="newTitle" :before-close="handleClose" width="30%">
      <el-form :model="newForm" label-width="auto" label-position="left" ref="siteOpenRef" :rules="rules">
        <el-form-item label="上级节点" prop="fatherId" required>
          <el-tree-select v-model="newForm.fatherId" :data="fatherList" :props="treeProps" value-key="menuId"
            placeholder="选择" check-strictly />
        </el-form-item>
        <el-form-item label="标签类型" prop="menuType" required>
          <el-select v-model="newForm.menuType" placeholder="请选择" @change="handleMenuTypeChange">
            <el-option v-for="dict in sys_tag_type" :key="dict.value" :label="dict.label" :value="dict.value"
              :disabled="dict.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="direction = true" v-if="showEditor">文本编辑</el-button>
        </el-form-item>
        <el-form-item :label="sys_tag_type.find(
          (e) => e.value === newForm.menuType
        )?.label" prop="menuTypeAssociationId" :required="requiredList
          " v-if="requiredList">
          <el-space spacer=" ">
            <el-text>{{ menuTypeAssociationIdFrom?.name }}</el-text>
            <el-button type="primary" @click="addListId">新增</el-button>
          </el-space>
          <!-- <el-tree-select v-model="newForm.menuTypeAssociationId" :data="publicList" :props="newTreeProps"
            value-key="id" placeholder="选择" check-strictly @change="changeTree" /> -->
        </el-form-item>
        <el-form-item label="页面链接" prop="nameUrl">
          <el-input v-model.trim="newForm.nameUrl" placeholder="请输入" :disabled="urlDisabled" />
        </el-form-item>

        <el-form-item label="状态" prop="status" required>
          <el-switch v-model="newForm.status" :active-value="1" :inactive-value="0" active-text="开启" inactive-text="关闭"
            inline-prompt />
        </el-form-item>
        <el-form-item label="图片" prop="newImage" v-if="showImage">
          <image-upload @baseUrl="handleBaseUrl" v-model="newForm.newImage" :limit="1" />
        </el-form-item>

        <el-form-item prop="newForm.descriptions" v-if="!showEditor">
          <MoreLanguage :newList="newForm.descriptions" :showControls="true" label="名称"></MoreLanguage>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleSure"> 确定 </el-button>
        <el-button @click="handleClose">取消</el-button>
      </template>
    </el-dialog>
    <el-drawer v-model="direction" title="文本编辑" :before-close="handleCloseDrawer">
      <el-tabs v-model="activeName">
        <el-tab-pane v-for="(item, index) in newForm.descriptions" :key="index" :label="sys_language_type.find((e) => e.id === item.languageId)?.description
          " :name="index">
          <el-input v-model="item.name" placeholder="请输入" style="margin: 10px 0">
            <template #prepend>名称</template>
          </el-input>
          <Editor v-model="item.content" :height="300" />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
    <PublicList :from="menuTypeAssociationIdFrom" :newType="typeList" @publicListSure="publicListSure"
      @publicListCancel="publicListCancel" :showList="showList" :websiteId="props.websiteId"
      :languageId="props.languageId">
    </PublicList>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from "vue";
import { slugify } from "transliteration";
import PublicList from "./publicList.vue";
const emits = defineEmits(["handleClose", "handleSure"]);
const { proxy } = getCurrentInstance();
const { sys_tag_type } = proxy.useDict("sys_tag_type");
const newTitle = ref("新增"); //名称
const showImage = ref(false); //是否显示图片
const direction = ref(false); //方向
const showEditor = ref(false); //显示文本编辑按钮
const sys_language_type = ref([]); //语言类型
const editLanguageList = ref([]); //编辑才会用到这个语言列表数据和详情的语言的列表数据匹配
const activeName = ref(0); //tab标签

const publicList = ref([]); //公共列表数据
const menuTypeAssociationIdFrom = ref({}); //公共赋值数据
const typeList = ref('')
const showList = ref(false)//默认不显示，列表弹出框显示


const siteProductSortList = ref([]); //商品分类列表数据
const siteProductList = ref([]); //商品列表数据
const articlesList = ref([]); //文章列表数据
const brandList = ref([]); //品牌列表数据
const requiredList = ref(false)//默认选择的列表数据是false
const urlDisabled = ref(true)//默认url是禁止输入的，只有自定义链接是可以输入的
const basicDate = ref({})//基础信息数据
const newUrl = ref('')

const newForm = ref({
  websiteId: null, //网站关联ID
  menuType: "text", //菜单类型
  placeType: "", //位置类型
  nameUrl: "", //名字的链接地址
  fatherId: 0, //父级Id
  descriptions: [],
  image: "",
  status: 1, //默认显示开启
  newImage: "", //需要删除
  seq: 0,
  menuTypeAssociationId: null,//选择的列表数据的id
});
const fatherList = ref([]);
const props = defineProps({
  TagVisible: {
    type: Boolean,
    default: false,
  },
  // 传值数据对象
  publicFrom: {
    type: Object,
    default: {},
  },
  newType: {
    type: String,
    default: "",
  },
  websiteId: {
    type: String,
    default: "",
  },
  languageId: {
    type: String,
    default: "",
  }
});

watch(
  () => props.TagVisible,
  () => {
    if (!props.TagVisible) return;

    getFatherList(); //获取父级列表信息
    handleTag();
    if (Object.keys(props.publicFrom).length) {
      newTitle.value = "编辑";
      getBasics(); //获取基础信息
    } else {
      if (props.newType === "top") {
        showImage.value = true;
      } else {
        showImage.value = false;
      }
      newTitle.value = "新增";
      getBasics(); //获取基础信息
    }
  }
);

// 确定
const handleSure = () => {
  proxy.$refs["siteOpenRef"].validate((valid) => {
    if (!valid) return;

    newForm.value.websiteId = proxy.websiteId;
    newForm.value.placeType = proxy.newType;

    if (!proxy.publicArray(newForm.value.descriptions))
      return proxy.$modal.msgError("请完整填写多语言");
    if (props.newType === "top") {
      handleHeard(); //站首标签处理
    } else {
      newForm.value.descriptions = newForm.value.descriptions.map((e) => {
        return {
          ...e,
          content: encodeURIComponent(e.content),
        };
      });
      handleHeard();
    }
  });
};
// 站首标签处理
const handleHeard = () => {
  if (newTitle.value === "新增") {
    publicAdd();
  } else {
    publicUpdate();
  }
};
onMounted(() => {
  getList()
})

const getList = () => {
  // 查询参数
  var from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      websiteId: Number(props.websiteId),
      languageId: Number(props.languageId),
      fatherId: 0,
    },
  };
  site.general
    .sitecategoryList({
      data: from,
    })
    .then((res) => {//商品分类
      siteProductSortList.value = res.data;
    });
  site.general
    .sitewebsiteproductList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//商品
      siteProductList.value = res.data
      // console.log(siteProductList.value, '商品');
    });

  site.general
    .sitearticleList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//文章
      if (res.code === 200 && res.data?.length) {
        res.data = res.data.map(e => {
          return {
            ...e,
            name: e.title
          }
        })
      }
      articlesList.value = res.data
    })

  site.general
    .sitewebsitebrandList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//商品品牌
      if (res.code === 200 && res.data?.length) {
        res.data = res.data.map(e => {
          return {
            ...e,
            name: e.commonName
          }
        })
      }
      brandList.value = res.data;
      // console.log(brandList.value, '商品品牌');
    });
}

const getBasics = () => {// 获取基础信息
  site.general
    .sitewebsiteGetbyid({
      pathParams: {
        id: Number(props.websiteId),
      },
    })
    .then((res) => {
      basicDate.value = res.data
      if (newTitle.value == "新增") {
        newForm.value.descriptions = [];
        if (res.data.languageIds.length) {
          res.data.languageIds.forEach((e) => {
            newForm.value.descriptions.push({
              languageId: e,
              name: '',
              content: "",
            });
          });
        }
      } else {
        editLanguageList.value = res.data.languageIds;
        getDetails(); //获取详情信息
      }
    });
};
// 获取父级数据
const getFatherList = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      websiteId: Number(props.websiteId),
      placeType: props.newType,
    },
  };
  site.general
    .site_website_menuList({
      data: from,
    })
    .then((res) => {
      if (res.data?.length) {
        res.data = addLevelToTree(res.data);
      }
      fatherList.value = addObjectToNewArrayIfNotExists(res.data);
    });
  product.language.languageList().then((res) => {  // 获取语言列表
    sys_language_type.value = res.data;
  });
};
const getDetails = () => {
  site.general
    .site_website_menuGetbyid({
      pathParams: {
        id: props.publicFrom.id,
      },
    })
    .then((res) => {
      publicMenuTypeAssociationId(res.data.menuType)
      processing(res.data.menuType,res.data.menuTypeAssociationId)
      newForm.value.websiteId = res.data.websiteId;
      newForm.value.menuType = res.data.menuType; //菜单类型
      newForm.value.menuTypeAssociationId = res.data.menuTypeAssociationId;
      newForm.value.placeType = res.data.placeType;
      newForm.value.nameUrl = res.data.nameUrl
      newUrl.value = res.data.nameUrl
      newForm.value.fatherId = res.data.fatherId;
      newForm.value.status = res.data.status;
      newForm.value.seq = res.data.seq;
      newForm.value.image = res.data.collocationLines[0]?.image;
      newForm.value.newImage = res.data.collocationLines[0]?.host;
      newForm.value.descriptions = [];
      newForm.value.descriptions = mergeArrays(
        res.data.descriptions,
        editLanguageList.value
      );
      if (res.data.placeType === "top") {
        showImage.value = true;
      } else {
        showImage.value = false;
      }
      if (res.data.placeType === "bottom" && res.data.menuType === "article") {
        showEditor.value = true;
      } else {
        showEditor.value = false;
      }
    });
};
const publicAdd = () => {
  site.general
    .site_website_menuAdd({
      data: newForm.value,
    })
    .then((res) => {
      console.log(res);
      if (res.code === 200) {
        showImage.value = false;
        showEditor.value = false;
        menuTypeAssociationIdFrom.value = {}
        proxy.$message.success("添加成功");
        proxy.resetForm("siteOpenRef");
        emits("handleSure");
      }
    });
};
const publicUpdate = () => {
  site.general
    .site_website_menuUpdate({
      pathParams: {
        id: props.publicFrom.id,
      },
      data: newForm.value,
    })
    .then((res) => {
      console.log(res);
      if (res.code === 200) {
        showImage.value = false;
        showEditor.value = false;
        menuTypeAssociationIdFrom.value = {}
        proxy.$message.success("修改成功");
        proxy.resetForm("siteOpenRef");
        emits("handleSure");
      }
    });
};


// 菜单类型改变
const handleMenuTypeChange = (val) => {
  if (props.newType === "bottom" && val === "article") {//是站尾并且是文本编辑
    showEditor.value = true;
  } else {
    showEditor.value = false;
  }

  newForm.value.menuTypeAssociationId = null
  newForm.value.nameUrl = "";
  menuTypeAssociationIdFrom.value = {}
  publicMenuTypeAssociationId(val)
  publicMenuTypeKey(val)
};
// 照片的host赋值
const handleBaseUrl = (val) => {
  newForm.value.image = val.url;
};
// 取消
const handleClose = () => {
  proxy.resetForm("siteOpenRef");
  showImage.value = false;
  showEditor.value = false;
  requiredList.value = false
  urlDisabled.value = true
  newForm.value.websiteId = null;
  newForm.value.menuType = "text";
  newForm.value.placeType = "";
  newForm.value.nameUrl = "";
  newForm.value.fatherId = 0;
  newForm.value.descriptions = [];
  newForm.value.image = "";
  newForm.value.status = 1;
  newForm.value.seq = 0;
  newForm.value.newImage = "";
  menuTypeAssociationIdFrom.value = {}
  emits("handleClose");
};
var rules = {
  menuTypeAssociationId: [{ required: true, message: "请选择", trigger: "blur" }],
};
const handleCloseDrawer = () => {
  const { name } = newForm.value.descriptions.find(e => e.languageId == basicDate.value.languageId)
  if (newTitle.value === '新增') {
    newForm.value.nameUrl = `/article/${formatUrl(name)}-a-`
  } else {
    newForm.value.nameUrl = `/article/${formatUrl(name)}-a-${newUrl.value.split("-a-")[1]}`
  }
  direction.value = false;
};
// 自定义 props
const treeProps = {
  label: "name",
  value: "id",
  children: "children",
  disabled: (data) => {
    return disableThirdLevel(data);
  },
};

const disableThirdLevel = (data) => {
  if (data.status && !data.level >= 3) {
    return false;
  } else {
    return data.level >= 3;
  }
};
const handleTag = () => {
  sys_tag_type.value = sys_tag_type.value.map((code) => {
    return {
      ...code,
      disabled: false,
    };
  });
  if (props.newType === "top") {
    sys_tag_type.value.find((e) => e.value === "article").disabled = true;
  } else {
    sys_tag_type.value.find((e) => e.value === "article").disabled = false;
  }
};
const mergeArrays = (descriptions, languageIds) => {
  // 创建一个新的数组来存储结果
  let newArray = [];
  const descriptionsById = new Map(
    descriptions.map((item) => [
      item.languageId,
      {
        languageId: item.languageId,
        name: item.name,
        content: decodeURIComponent(item.content),
      },
    ])
  );
  languageIds.forEach((languageId) => {
    if (descriptionsById.has(languageId)) {
      // 如果 languageId 存在于 descriptions 中，则复制对应的简化对象到 newArray
      newArray.push(descriptionsById.get(languageId));
    } else {
      // 如果 languageId 不存在于 descriptions 中，则创建新对象并添加到 newArray
      newArray.push({ languageId: languageId, name: "", content: "" });
    }
  });
  return newArray;
};
// 上级节点加层级
const addLevelToTree = (tree, parentLevel = 0) => {
  return tree.map((item) => ({
    ...item,
    level: parentLevel + 1,
    children: item.children
      ? addLevelToTree(item.children, parentLevel + 1)
      : undefined,
  }));
};
// 上级节点没有数据时，加入顶级节点数据
const addObjectToNewArrayIfNotExists = (arr) => {
  let newObj = {
    name: "顶级节点",
    status: 1,
    id: 0,
  };
  const isDuplicateId = arr.some((item) => item.id === newObj.id);
  if (!isDuplicateId) {
    return [newObj, ...arr];
  } else {
    return [...arr]; // 返回原数组的副本
  }
};
const changeTree = (e) => {
  newForm.value.nameUrl = "";
  const { menuType } = newForm.value
  const { elTagClass, value } = sys_tag_type.value.find(
    (e) => e.value === menuType
  )
  if (menuType === "category") {//商品分类====分类名称-c-分类id，树形结构
    const { name, id } = findNodeById(publicList.value, e)
    newForm.value.nameUrl = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (menuType === "product") {//商品=== 商品名称-p-商品id
    const { name, id } = siteProductList.value.find(item => item.id === e)
    newForm.value.nameUrl = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (menuType === "news_detail") {//文章详情===博客名称-n-博客id
    const { name, id } = articlesList.value.find(item => item.id === e)
    newForm.value.nameUrl = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (menuType === "brand") {//品牌详情:  品牌名称-b-品牌id
    const { name, id } = brandList.value.find(item => item.id === e)
    newForm.value.nameUrl = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  }
}
const publicMenuTypeAssociationId = (val) => {
  urlDisabled.value = true
  // console.log(val, '菜单类型改变');
  if (val === "category") {//商品分类====分类名称-c-分类id
    requiredList.value = true
    publicList.value = siteProductSortList.value
  } else if (val === "product") {//商品=== 商品名称-p-商品id
    requiredList.value = true
    publicList.value = siteProductList.value

  } else if (val === "news_detail") {//文章详情===博客名称-n-博客id
    requiredList.value = true
    publicList.value = articlesList.value

  } else if (val === "brand") {//品牌详情:  品牌名称-b-品牌id
    requiredList.value = true
    publicList.value = brandList.value

  } else if (val === "article") {
    //站首尾跳链接的: nameUrl页面链接：默认语言的多语言名称-a-默认语言的多语言id(文本编辑)
    requiredList.value = false
    publicList.value = []
    console.log(newForm.value.descriptions, '文本编辑');
  } else if (val === 'link') {
    requiredList.value = false
    publicList.value = []
    urlDisabled.value = false
  } else {
    requiredList.value = false
    publicList.value = []
  }
}

const publicMenuTypeKey = (val) => {
  let newTypeUrl = sys_tag_type.value.find(e => e.value === val)?.elTagClass
  if (val === 'brand_list') {//品牌
    newForm.value.nameUrl = newTypeUrl
  } else if (val === "news") {//文章
    newForm.value.nameUrl = newTypeUrl
  } else if (val === "account") {//账户
    newForm.value.nameUrl = newTypeUrl
  } else if (val === "order") {//订单
    newForm.value.nameUrl = newTypeUrl
  } else if (val === "wishlist") {//愿望单
    newForm.value.nameUrl = newTypeUrl
  }
}

const findNodeById = (tree, id) => {
  for (let node of tree) {
    if (node.id === id) {
      return node; // 找到目标节点
    }
    if (node.children) {
      let found = findNodeById(node.children, id);
      if (found) return found; // 递归查找子节点
    }
  }
  return null; // 没找到
}
function formatUrl(input) {
  return slugify(input, { separator: '-' });
}
const processing=(menuType,menuTypeAssociationId)=>{
  if (menuType === "category") {//商品分类====分类名称-c-分类id，树形结构
    publicListSure(siteProductSortList.value.find(e=>e.id===menuTypeAssociationId))
  } else if (menuType === "product") {//商品=== 商品名称-p-商品id
    publicListSure(siteProductList.value.find(e=>e.id===menuTypeAssociationId))
  } else if (menuType === "news_detail") {//文章详情===博客名称-n-博客id
    publicListSure(articlesList.value.find(e=>e.id===menuTypeAssociationId))
  } else if (menuType === "brand") {//品牌详情:  品牌名称-b-品牌id
    publicListSure(brandList.value.find(e=>e.id===menuTypeAssociationId))
  }
}
const addListId = () => {
  showList.value = true
  typeList.value = newForm.value.menuType

}
const publicListSure = (row) => {
  showList.value = false
  menuTypeAssociationIdFrom.value = row
  newForm.value.menuTypeAssociationId = row.id
  changeTree(row.id)
}

const publicListCancel = () => {
  showList.value = false
}
</script>
